package com.vincce.fitness.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vincce.fitness.constant.WechatConstant;
import com.vincce.fitness.core.util.WechatUtil;
import com.vincce.fitness.entity.Account;
import org.apache.http.client.fluent.Request;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by henry on 5/5/14.
 */
@Repository
public class WechatRunner {

	/**
	 * 高级接口获取用户信息
	 * @param openid
	 * @return
	 * @throws IOException
	 */
	public String getUserInfo(String openid,Account account) throws IOException {
		return sendGet(WechatConstant.USER_INFO_URL + "&openid=" + openid,account);
	}

	/**
	 * oauth获取openid
	 * @param code
	 * @return
	 * @throws IOException
	 */
	public String fetchOauthOpenId(String code,Account account) throws IOException {
		String access_token_fetch_url = String.format("%s/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", WechatConstant.URL_PREFIX, account.getAppId(), account.getAppSecret(),"%s");
		JSONObject wechatAccessToken = JSON.parseObject(WechatUtil.HttpUtil.fetch(Request.Get(String.format(access_token_fetch_url, code))));
		return wechatAccessToken.getString("openid");
	}























	/**==========以下是基本调用===========**/
	private String fetchAccessToken(Account account) throws IOException {
		String access_token_fetch_url = String.format("%s/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",WechatConstant.URL_PREFIX,account.getAppId(),account.getAppSecret());
		JSONObject wechatAccessToken = JSON.parseObject(WechatUtil.HttpUtil.fetch(Request.Get(access_token_fetch_url)));
		String	accessToken = wechatAccessToken.getString("access_token");
		return accessToken;
	}

	private String sendPost(String url, String body,Account account) throws IOException {
		String accessToken = fetchAccessToken(account);
		if (accessToken == null) {
			return null;
		}
		return WechatUtil.HttpUtil.fetch(Request.Post(String.format(url, accessToken)), body);
	}

	private String sendGet(String url,Account account) throws IOException {
		String accessToken = fetchAccessToken(account);
		if (accessToken == null) {
			return null;
		}
		return WechatUtil.HttpUtil.fetch(Request.Get(String.format(url, accessToken)));
	}

	private InputStream sendGetInputStream(String url,Account account) throws IOException {
		String accessToken = fetchAccessToken(account);
		if (accessToken == null) {
			return null;
		}
		return WechatUtil.HttpUtil.fetchInputStream(Request.Get(String.format(url, accessToken)));
	}

}
